package com.dpwgc.provider.server;

import com.dpwgc.provider.mapper.DnMapper;
import com.dpwgc.provider.model.Dn;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQPushConsumerLifecycleListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * RocketMQ-消息队列-监听模块
 */
@Component
public class RocketMQServer {

    /**
     * 监听消息-消费信息
     */
    @Slf4j
    @Component
    @RocketMQMessageListener(topic = "broker-a", consumerGroup = "dn-group")
    public static class PopMessage implements RocketMQListener<Dn>, RocketMQPushConsumerLifecycleListener {

        @Autowired
        DnMapper dnMapper;

        //从消息队列中取出消息
        @Override
        public void onMessage(Dn dn) {
            try{
                if(dn.getDnUserUuid() != null) {
                    //将代拿订单插入数据库
                    dn.setDnUuid(UUID.randomUUID().toString().replaceAll("-", ""));
                    dnMapper.createDn(dn);
                }

            }catch(Exception e){
                //抛出异常后，MQClient会返回ConsumeConcurrentlyStatus.RECONSUME_LATER,这条消息会再次尝试消费
                System.err.println("消息确认失败："+e);
                throw new RuntimeException(e);
            }
        }
        @Override
        public void prepareStart(DefaultMQPushConsumer consumer) {
            //拉取间隔，单位:毫秒
            consumer.setPullInterval(1000);
            //每次拉取的消息数
            consumer.setPullBatchSize(5);
        }
    }
}
